package org.dut.community.controller;

import org.dut.community.entity.Event;
import org.dut.community.entity.User;
import org.dut.community.event.EventProducer;
import org.dut.community.service.LikeService;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.CommunityUtil;
import org.dut.community.util.HostHolder;
import org.dut.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstant {
    @Autowired
    private LikeService likeService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    @ResponseBody
    @RequestMapping(path = "/like", method = RequestMethod.POST)
    public String like(int entityType, int entityId,int entityUserId,int postId) {
        User user = hostHolder.getUser();
        if(user == null) {
            return CommunityUtil.getJSONString(403, "未登录");
        }
        likeService.like(user.getId(), entityType, entityId,entityUserId);
        // 当前实体点赞数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        // 当前用户点赞状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        Map<String,Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        // 事件--仅当用户点赞时触发
        if(likeStatus == 1) {
            Event event = Event.builder()
                    .topic(TOPIC_LIKE)
                    .userId(user.getId())
                    .entityType(entityType)
                    .entityId(entityId)
                    .entityUserId(entityUserId)
                    .build().setData("postId", postId);
            eventProducer.fireEvent(event);
            // 点赞帖子 增加分数
            if(entityType == ENTITY_TYPE_POST) {
                String redisKey = RedisKeyUtil.getPostScoreKey();
                redisTemplate.opsForSet().add(redisKey, postId);
            }
        }

        return CommunityUtil.getJSONString(0, null,map);
    }
}
